package com.li.algorithm.leetcode.hot100;

public class Test28 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode();
        int carry = 0;
        ListNode p = head;
        while (l1 != null || l2 != null) {
            int v1 = (l1 != null) ? l1.val : 0;
            int v2 = (l2 != null) ? l2.val : 0;
            p.val = (v1 + v2 + carry) % 10;
            carry = (v1 + v2 + carry) / 10;
            l1 = l1 != null ? l1.next : null;
            l2 = l2 != null ? l2.next : null;
            if (l1 != null || l2 != null) {
                p.next = new ListNode();
                p = p.next;
            }
        }
        if (carry > 0) {
            p.next = new ListNode(carry);
        }
        return head;
    }

    public static void main(String[] args) {
        //4, 5, 6
        ListNode l1 = new ListNode(9);
        ListNode p = l1;
        for (int i = 0; i < 7; i++) {
            p.next = new ListNode(9);
            p = p.next;
        }
        //5, 6, 7, 8, 9
        ListNode l2 = new ListNode(9);
        p = l2;
        for (int i = 0; i < 4; i++) {
            p.next = new ListNode(9);
            p = p.next;
        }
        ListNode result = new Test28().addTwoNumbers(l1, l2);
        while (result != null) {
            System.out.println(result.val);
            result = result.next;
        }

    }
}
